angular.module('BaseControl')

.directive("uploadfile", ["FileUploader", 'BaseFunction', '$cookies', function(FileUploader, BaseFunction, $cookies) {
    return {
        restrict: "E",  // 指令是一个元素 (并非属性)，备选项有"A"、"E" 和 "C"， "M" ,分别代表attribute、element、class和comment（默认值为"A"）
        scope: {
            value: '=?',
            size: '=?',
            uploader: '=?',
            uploadpath: '@?',   //服务器文件相对根目录路径
            change: '&'
        },
        templateUrl:
            'modules/Base/client/views/UploadFile.html',
        replace: true,          // 使用模板替换原始标记
        transclude: true,       // 不复制原始HTML内容
        controller: ['$scope', function($scope){
            $scope.UploadAPI = '/api/base/uploadFile';
            $scope.uploader =  new FileUploader({url: $scope.UploadAPI});
            $scope.uploader.headers["Authorization"] = 'Bearer ' + $cookies.get('U9USS')

            // FILTERS 
             $scope.uploader.filters.push({name: 'customFilter', 
                //1，客户端上传文件时触发，每上传一个触发一次，限制上传的文件个数
                 fn: function(fileItem, options) { 
                     return this.queue.length < 10;
                 } 
             });     

             //客户端上传失败时触发
             $scope.uploader.onWhenAddingFileFailed = function(item, filter, options) { 
             }; 
             //2，客户端上传完毕时触发
             $scope.uploader.onAfterAddingFile = function(fileItem) {
                $scope.DisplayText = fileItem.file.name;
                $scope.size = fileItem.file.size;
                $scope.IsNoUpload = true;
                $scope.Progress = 0;
                //在此可添加其他上传参数
                if($scope.FileName != ""){
                    fileItem.formData.push({"FileName": $scope.FileName});
                }
                if($scope.IsDeleteOldFile){
                    if($scope.OldFileName != null && $scope.OldFileName != undefined && $scope.OldFileName != ""){
                        fileItem.formData.push({"DeleteFileName": $scope.OldFileName});
                    }
                }                

                $scope.uploader.queue = [fileItem];
                if($scope.IsRealTime){
                    fileItem.upload();
                }
             }; 
             //3，客户端所有文件上传完毕时触发
             $scope.uploader.onAfterAddingAll = function(addedFileItems) { 
             }; 
             //（1）上传给服务器之前触发
             $scope.uploader.onBeforeUploadItem = function(item) { 
             }; 
             //（2）单个文件上传给服务器时，进度发生变化触发
             $scope.uploader.onProgressItem = function(fileItem, progress) { 
             };
             //（3）全部文件上传给服务器时，总进度发生变化触发
             $scope.uploader.onProgressAll = function(progress) {
                $scope.Progress = progress;
             }; 
             //(4)单个文件上传，成功时触发
             $scope.uploader.onSuccessItem = function(fileItem, response, status, headers) {
                if(response.status != undefined){
                    BaseFunction.alert(response.desc, "上传失败");
                }
                else{
                    if(response.Error){
                        BaseFunction.alert(response.Error.message, response.Error.title);
                    }
                    else{
                        $scope.DisplayText = $scope.value = $scope.OldFileName = response.Data.file.path;
                        $scope.IsNoUpload = false;
                        $scope.uploader.clearQueue();
                        $scope._IsUploadChange = true;
                    }
                }
             }; 
             //(4)单个文件上传服务器，失败时触发
             $scope.uploader.onErrorItem = function(fileItem, response, status, headers) { 
             };
             //单个文件上传，取消时触发
             $scope.uploader.onCancelItem = function(fileItem, response, status, headers) { 
             }; 
             //(5)单个文件上传完成时触发，包括上传失败
             $scope.uploader.onCompleteItem = function(fileItem, response, status, headers) { 
             }; 
             //(6)所有文件上传完成时触发，包括上传失败
             $scope.uploader.onCompleteAll = function() {
                if(!$scope.IsRealTime){
                    $scope.$parent.$digest();
                    completeFun();
                }
             }; 

            $scope.click = function() {
                $scope.FileInputElement.click();
            };
            $scope.removeClick = function() {
                $scope.uploader.clearQueue();
                $scope.Progress = 0;
                $scope.IsNoUpload = false;
                $scope.DisplayText = $scope.OldFileName;
                $scope.size = $scope.OldSize;
            };
            var completeFun;
            $scope.uploader.save = function(fun){
                if($scope.uploader.queue.length > 0){
                    completeFun = fun;
                    $scope.uploader.uploadAll();
                }
                else{
                    fun();
                }
            };
        }],
        link: function (scope, element, attrs) {
            scope.Enabled = true;
            scope.Visible = true;
            scope.IsEmpty = true;

            scope.FileName = "";           
            scope.OldFileName = scope.value;
            scope.OldSize = scope.size;

            scope.DisplayText = scope.value;
            scope.Progress = 0;
            scope.IsRealTime = true;
            scope.IsNoUpload = false;
            scope.IsDeleteOldFile = true;
            scope.FileInputElement = null;
            scope._IsUploadChange = false;  //是否是上传完成触发更改的文件名

            if (attrs["filename"] != undefined && attrs["filename"].trim() != "") {
                scope.FileName = attrs["filename"].trim();
            }
            if (attrs["isrealtime"] != undefined && attrs["isrealtime"].trim().toLocaleLowerCase() == "false") {
                scope.IsRealTime = false;
            }
            if (attrs["isdeleteoldfile"] != undefined && attrs["isdeleteoldfile"].trim().toLocaleLowerCase() == "false") {
                scope.IsDeleteOldFile = false;
            }

            scope.FileInputElement = element[0].children[1];

            scope.$watch(function(){
                return scope.value;
            },
            function(){
                scope.DisplayText = scope.OldFileName = scope.value;
                if(scope._IsUploadChange){
                    scope._IsUploadChange = false;
                }
                else{
                    scope.Progress = 0;
                }
            });

            var watch = scope.$watch(
                function(){
                    return attrs["enabled"];
                },
                function(){
                    if (attrs["enabled"] != undefined && attrs["enabled"].trim().toLocaleLowerCase() == "false") {
                        scope.Enabled = false;
                    }
                    else{
                        scope.Enabled = true;
                    }
                }
            );
            //watch();

            scope.$watch(
                function(){
                    return attrs["visible"]
                },
                function(){
                    if (attrs["visible"] != undefined && attrs["visible"].trim().toLocaleLowerCase() == "false") {
                        scope.Visible = false;
                    }
                    else{
                        scope.Visible = true;
                    }
                }
            );
        }
    }
}]);
